﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TFS2010ServiceProvider.Classes;
using System.Xml.Serialization;
using System.Xml;
using System.Security.Principal;
using System.Text;

namespace TFS2010ServiceProvider
{
    /// <summary>
    /// TFS 2010 Service Provider
    /// </summary>
    [WebService(Namespace = "http://bssp.ru/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service : System.Web.Services.WebService
    {
        /// <summary>
        /// Get work items
        /// </summary>
        /// <param name="query">string as encoded URL (UTF-8)</param>
        /// <param name="teamProjectCollectionUrl">string as encoded URL (UTF-8) example: "http%3A%2F%2Ftfs%3A8080%2Ftfs%2Fspf+2010"</param>
        /// <returns></returns>
        [WebMethod]
        public string GetWorkItems(string query, string teamProjectCollectionUrl)
        {
            var wItems = new WorkItems();

            var wItemsList = new List<TFS2010ServiceProvider.Classes.WorkItem>();

            // Obtain the authenticated user's Identity
            WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
            WindowsImpersonationContext ctx = null;
            try
            {
                // Start impersonating
                ctx = winId.Impersonate();
                                
                // Access resources using the identity of the authenticated user                               
                var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(HttpUtility.UrlDecode(teamProjectCollectionUrl)));

                tfs.EnsureAuthenticated();

                var store = tfs.GetService<WorkItemStore>();

                WorkItemCollection results = store.Query(HttpUtility.UrlDecode(query));

                foreach (Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem wi in results)
                {                    
                    wItemsList.Add(new TFS2010ServiceProvider.Classes.WorkItem() { Type = wi.Type.Name, Title = wi.Title, State = wi.State, AssignedTo = wi[CoreField.AssignedTo] != null ? wi[CoreField.AssignedTo].ToString() : string.Empty, AreaPath = wi.AreaPath });
                }
            }            
            catch (Exception e)
            {
                return e.Message + e.InnerException + e.StackTrace;
            }
            finally
            {
                // Revert impersonation
                if (ctx != null)
                {
                    ctx.Undo();
                }
            }
            
            // Back to running under the default ASP.NET process identity
            wItems.Items = wItemsList.ToArray();

            return SerializationHelper.ToXml(wItems, typeof(WorkItems));            
        }
    }
}